package com.virus.mall.controller.admin;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.corba.se.impl.naming.cosnaming.NamingUtils;
import com.virus.mall.model.Reply;
import com.virus.mall.model.Result;
import com.virus.mall.model.Spec;
import com.virus.mall.model.Type;
import com.virus.mall.model.bo.*;
import com.virus.mall.model.vo.AddSpecVo;
import com.virus.mall.model.vo.GoodsGetByTypeVo;
import com.virus.mall.model.vo.GoodsGetInfoVo;
import com.virus.mall.model.vo.SpecGetVo;
import com.virus.mall.service.GoodsService;
import com.virus.mall.service.impl.GoodsServiceImpl;
import com.virus.mall.utils.FileUploadUtils;
import com.virus.mall.utils.HttpUtils;
import org.omg.PortableInterceptor.INACTIVE;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Classname GoodsServlet
 * @Description 商品模块servlet
 * @Date 2021/4/16 22:45
 * @Created by virus
 */
@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/admin/goods/", "");
        if (op.equals("imgUpload")) {
            imgUpload(request, response);
        } else if (op.equals("addGoods")) {
            addGoods(request, response);
        } else if (op.equals("addType")) {
            addType(request, response);
        } else if (op.equals("addSpec")) {
            addSpec(request, response);
        } else if (op.equals("updateGoods")) {
            updateGoods(request, response);
        } else if (op.equals("deleteSpec")) {
            deleteSpec(request, response);
        } else if (op.equals("reply")) {
            reply(request, response);
        }
     }

    /**
     * 增加商品或编辑商品时上传图片到数据库
     * @param request
     * @param response
     * @throws IOException
     */
    private void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = FileUploadUtils.upload(request);
        String fileUrl = (String) map.get("file");
        System.out.println("surprise！！！即将响应图片 > V <");
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(fileUrl)));
    }

    /**
     * 在一类型下增加商品
     * @param request
     * @param response
     * @throws IOException
     */
    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddGoodsBo addGoodsBo;
        try {
            addGoodsBo = objectMapper.readValue(requestBody, AddGoodsBo.class);
        } catch (Exception e) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数类型错误")));
            return;
        }
        if (addGoodsBo.getName() == null || addGoodsBo.getName().equals("")) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("商品名不能为空")));
            return;
        }
        if (addGoodsBo.getImg() == null || addGoodsBo.getImg().equals("")) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("传入图片不能为空")));
            return;
        }
        for (Spec spec : addGoodsBo.getSpecList()) {
            if (spec.getStockNum() <= 0 || spec.getUnitPrice() <= 0) {
                response.getWriter().println(objectMapper.writeValueAsString(Result.error("库存与价格不可为负数")));
                return;
            }
        }
        boolean result = goodsService.addGoods(addGoodsBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("增加商品信息失败")));
        }
    }

    /**
     * 增加类型
     * @param request
     * @param response
     * @throws IOException
     */
    private void addType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddTypeBo addTypeBo = objectMapper.readValue(requestBody, AddTypeBo.class);
        boolean result = goodsService.addType(addTypeBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("增加商品出错")));
        }
    }

    /**
     * 在一商品下增加规格
     * @param request
     * @param response
     * @throws IOException
     */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddSpecBo addSpecBo = null;
        try {
            addSpecBo = objectMapper.readValue(requestBody, AddSpecBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数类型不正确")));
            return;
        }
        if (addSpecBo.getStockNum() <= 0 || addSpecBo.getUnitPrice() <= 0) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("库存与价格不可设置负数")));
            return;
        }
        AddSpecVo addSpecVo = goodsService.addSpec(addSpecBo);
        if (addSpecVo == null) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("增加规格未成功,可能存在重复的规格名")));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok(addSpecVo)));
        }
    }

    /**
     * 更新商品信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsUpdateBo goodsUpdateBo = null;
        try {
            goodsUpdateBo = objectMapper.readValue(requestBody, GoodsUpdateBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("传入参数错误")));
            return;
        }
        if (goodsUpdateBo.getName() == null || goodsUpdateBo.getName().equals("")) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("商品名不能为空")));
            return;
        }
        if (goodsUpdateBo.getImg() == null || goodsUpdateBo.getImg().equals("")) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("传入图片不能为空")));
            return;
        }
        for (SpecGetVo specGetVo : goodsUpdateBo.getSpecList()) {
            if (specGetVo.getStockNum() < 0 || specGetVo.getUnitPrice() < 0) {
                response.getWriter().println(objectMapper.writeValueAsString(Result.error("库存与价格不可为负数")));
                return;
            }
        }
        boolean result = goodsService.updateGoods(goodsUpdateBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("商品更新未成功")));
        }
    }

    /**
     * 删除某商品规格
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        SpecDeleteBo specDeleteBo = null;
        try {
            specDeleteBo = objectMapper.readValue(requestBody, SpecDeleteBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("请求参数不正确")));
            return;
        }
        boolean result = goodsService.deleteSpec(specDeleteBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("删除商品规格不成功")));
        }
    }

    /**
     * 回复商品问答
     * @param request
     * @param response
     * @throws IOException
     */
    private void reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        ReplyBo replyBo = null;
        try {
            replyBo = objectMapper.readValue(requestBody, ReplyBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数类型错误")));
        }
        boolean result = goodsService.reply(replyBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("回复留言失败")));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/admin/goods/", "");
        if (op.equals("getType")) {
            getType(request, response);
        } else if (op.startsWith("getGoodsByType")) {
            getGoodsByType(request, response);
        } else if (op.startsWith("deleteGoods")) {
            deleteGoods(request, response);
        } else if (op.startsWith("deleteType")) {
            deleteType(request, response);
        } else if (op.startsWith("getGoodsInfo")) {
            getGoodsInfo(request, response);
        } else if (op.equals("noReplyMsg")) {
            noReplyMsg(request, response);
        } else if (op.equals("repliedMsg")) {
            repliedMsg(request, response);
        }
    }

    /**
     * 获得商品类型信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> typeList = goodsService.getType();
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(typeList)));
    }

    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        List<GoodsGetByTypeVo> goodsList;
        try {
            goodsList = goodsService.getGoodsByType(Integer.parseInt(typeId));
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("请求参数错误")));
            return;
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(goodsList)));
    }

    /**
     * 删除某一商品信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        boolean result;
        try {
            result = goodsService.deleteGoods(Integer.parseInt(id));
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("传入参数错误")));
            return;
        }
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("删除商品信息错误")));
        }
    }

    /**
     * 删除商品类型
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeIdStr = request.getParameter("typeId");
        int typeId;
        try {
            typeId = Integer.parseInt(typeIdStr);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString("传入参数错误"));
            return;
        }
        boolean result = goodsService.deleteType(typeId);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("删除类目失败")));
        }
    }

    /**
     * 获得商品信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        GoodsGetInfoVo goodsGetInfoVo = null;
        try {
            goodsGetInfoVo = goodsService.getGoodsInfo(Integer.parseInt(id));
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数转化失败")));
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(goodsGetInfoVo)));
    }

    /**
     * 没有回复的商品问答的信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void noReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Reply> replies = goodsService.noReplyMsg();
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(replies)));
    }

    /**
     * 已回复商品问答的信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void repliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Reply> replies = goodsService.repliedMsg();
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(replies)));
    }
}
